import { TParamsMap } from '../type';
import { execaCommand } from 'execa';
import { isBuildInCommand, getParamsMap, fixSpawnNpmCommand } from './utils';

export * from './utils';

const npm = fixSpawnNpmCommand();

class Command {
    exec(command: string): Promise<unknown> {
        if (isBuildInCommand(command)) {
            try {
                const argv = command.split(' ');
                const task = argv[1];
                const paramsMap = getParamsMap(argv.slice(2));

                if (argv.length < 2) {
                    return Promise.reject(new Error('命令错误'));
                }

                // @ts-ignore
                const t = this[task];
                if (t) {
                    // @ts-ignore
                    return this[task](paramsMap);
                } else {
                    return Promise.reject(new Error('没有找到指令'));
                }

                // ...
            } catch (error) {
                return Promise.reject(error);
            }
        } else {
            return Promise.reject(new Error('非内置命令调用'));
        }
    }

    /**
     * 测试
     */
    hello() {
        console.log('Hello, Teletool');
    }

    /**
     * 安装
     *
     * @param params.entryDir - 入口目录，也是带有 package.json 的目录，完整的目录路径（必填）
     */
    async install(params: TParamsMap) {
        try {
            const { entryDir } = params;
            if (entryDir) {
                const cwd = entryDir as string;
                const command = `${npm} install`;
                const result = await execaCommand(command, { cwd: cwd || process.cwd() });
                return Promise.resolve(result.stdout);
            } else {
                throw new Error('参数不满足');
            }

            // ...
        } catch (error) {
            return Promise.reject(error);
        }
    }
}
const context = new Command();

// as buildInCommand
export default {
    context,
    isBuildInCommand,
};
